<template>
    
    <el-form ref="formRef" class="pl-3" :model="formData" label-width="80px" inline>
        
        <el-card class="!border-none flex flex-1 items-center justify-center" shadow="never">
            <div class=" w-[800px]">
                <div class=" text-lg	 mb-4">
                    基本信息
                </div>
                
                <div class="pl-3 grid grid-cols-2 gap-0">
                    <div>
                        <el-form-item label="工单类型" prop="afterSaleOrderType"
                                      :rules="[{required: true, message:'工单类型不可为空',trigger:'change'}]">
                            
                            <el-select class="w-56" v-model="formData.afterSaleOrderType">
                                <el-option v-for="item in afterSaleOrderConfig.afterSaleOrderType"
                                           :label="item.name"
                                           :value="item.code"/>
                            </el-select>
                        
                        
                        </el-form-item>
                    </div>
                    
                    <div>
                        <el-form-item label="来源" prop="source"
                                      :rules="[{required: true, message:'来源不可为空',trigger:'change'}]">
                            
                            <el-select class="w-56" v-model="formData.source" placeholder="请输入来源">
                                <el-option v-for="item in afterSaleOrderConfig.orderSourceConfig"
                                           :label="item.value"
                                           :value="item.name"/>
                            </el-select>
                        
                        </el-form-item>
                    </div>
                    
                    
                    <div>
                        <el-form-item label="渠道" prop="channel"
                                      :rules="[{required: true, message:'渠道不可为空',trigger:'change'}]">
                            <el-select class="w-56" v-model="formData.channel" placeholder="请输入渠道名称"
                                       clearable
                                       @change="handleChannelChange">
                                <el-option v-for="item in channelSelect"
                                           :label="item.value"
                                           :value="item.name"/>
                            </el-select>
                        
                        </el-form-item>
                    </div>
                    
                    <div>
                        <el-form-item label="店铺" prop="shopName"
                                      :rules="[{required: true, message:'店铺不可为空',trigger:'change'}]">
                            <el-select class="w-56" v-model="formData.shopName" placeholder="请输入店铺名称" clearable>
                                <el-option v-for="item in shopSelect"
                                           :label="item.value"
                                           :value="item.name"/>
                            </el-select>
                        
                        </el-form-item>
                    </div>
                
                </div>
            
            </div>
        </el-card>
        
        
        <el-card class="!border-none flex flex-1 items-center justify-center mt-2" shadow="never">
            <div class=" w-[800px]">
                <div class=" text-lg	 mb-4">订单信息</div>
                
                
                <div class="pl-3  grid grid-cols-2 gap-0">
                    <div>
                        <el-form-item label="订单号" prop="orderNumber"
                                      :rules="[{required: true, message:'订单号不可为空',trigger:'change'}]">
                            <el-input class="w-56" v-model="formData.orderNumber" placeholder="请输入订单信息"
                                      clearable/>
                            
                            <el-button @click="createSerialNumber"
                                       type="primary"
                                       link>
                                生成
                            </el-button>
                        </el-form-item>
                    </div>
                    
                    <div>
                        <el-form-item label="用户名称" prop="userName"
                                      :rules="[{required: true, message:'用户名称不可为空',trigger:'change'}]">
                            <el-input class="w-56" v-model="formData.userName" placeholder="请输入用户名称"
                                      clearable/>
                        </el-form-item>
                    </div>
                    
                    
                    <div>
                        <el-form-item label="用户电话" prop="userPhone"
                        
                                      :rules="[{required: true, message:'用户电话不可为空',trigger:'change'},
                                        { type: 'number', message: '用户电话必须是数字',trigger:'change' }]">
                            <el-input class="w-56" v-model.number="formData.userPhone" placeholder="请输入用户电话"
                                      clearable/>
                        </el-form-item>
                    </div>
                    
                    <div>
                        <el-form-item label="原因类别" prop="reason"
                                      :rules="[{required: true, message:'原因类别不可为空',trigger:'change'}]">
                            
                            <el-select class="w-56" v-model="formData.reason" placeholder="请输入原因类别">
                                <el-option v-for="item in afterSaleOrderConfig.orderCauseConfig"
                                           :label="item.value"
                                           :value="item.name"/>
                            </el-select>
                        
                        
                        </el-form-item>
                    </div>
                
                </div>
            
            </div>
        </el-card>
        
        
        <el-card class="!border-none flex flex-1 items-center justify-center mt-2" shadow="never">
            <div class=" w-[800px]">
                <div class=" text-lg	 mb-4">物流信息</div>
                
                
                <div class="pl-3  grid grid-cols-2 gap-0">
                    <div>
                        <el-form-item label="物流公司" prop="logisticCompany">
                            <el-input class="w-56" v-model.trim="formData.logisticCompany" placeholder="请输入物流公司"
                                      clearable/>
                        </el-form-item>
                    </div>
                    
                    <div>
                        <el-form-item label="物流单号" prop="logisticNumber">
                            <el-input class="w-56" v-model.trim="formData.logisticNumber" placeholder="请输入物流单号"
                                      clearable/>
                        </el-form-item>
                    </div>
                
                </div>
            
            </div>
        </el-card>
        
        
        <!--        收件人信息-->
        <el-card class="!border-none flex flex-1 items-center justify-center mt-2"
                 v-if="formData.afterSaleOrderType=== AfterSaleOrderTypeEnum.CONSIGNMENT" shadow="never">
            <div class=" w-[800px]">
                <div class=" text-lg	 mb-4">收件人信息</div>
                
                
                <div class="pl-3  grid grid-cols-2 gap-0">
                    
                    <div>
                        <el-form-item label="姓名" prop="addressInfo.userName"
                                      :rules="[{required: true, message:'收件人姓名不可为空',trigger:'change'}]">
                            <el-input class="w-56" v-model.trim="formData.addressInfo.userName"
                                      placeholder="请输入收件人姓名"
                                      clearable/>
                        </el-form-item>
                    </div>
                    
                    <div>
                        <el-form-item label="电话" prop="addressInfo.userPhone"
                                      :rules="[{required: true, message:'收件人电话不可为空',trigger:'change'},
                                       { type: 'number', message: '用户电话必须是数字' }]">
                            <el-input class="w-56" v-model.number.trim="formData.addressInfo.userPhone"
                                      placeholder="请输入收件人电话"
                                      clearable/>
                        </el-form-item>
                    </div>
                    
                    <div>
                        <el-form-item label="省市区" prop="addressInfoEnum"
                                      :rules="[{required: true, message:'省市区不可为空',trigger:'change'}]">
                            
                            <el-cascader
                                class="w-56"
                                placeholder="请选择省市区"
                                :options="afterSaleOrderConfig.addressTree"
                                v-model="formData.addressInfoEnum"
                                :props="{
                                  value: 'name',
                                  label: 'name',
                                  children: 'children',
                                  expandTrigger: 'hover' }"
                                @change="handleAddressChange"
                            />
                        </el-form-item>
                    
                    </div>
                    
                    <div>
                        <el-form-item label="详细地址" prop="addressInfo.address"
                                      :rules="[{required: true, message:'详细地址不可为空',trigger:'change'}]">
                            <el-input class="w-56" v-model="formData.addressInfo.address" placeholder="请输入详细地址"
                                      clearable/>
                        </el-form-item>
                    </div>
                
                </div>
            
            </div>
        </el-card>
        
        <!--        描述信息-->
        <el-card class="!border-none flex flex-1 items-center justify-center mt-2" shadow="never">
            <div class=" w-[800px]">
                <div class=" text-lg	 mb-4">描述信息</div>
                
                
                <div class="pl-3  grid grid-cols-1 ">
                    <div>
                        <el-form-item label="原因描述" prop="description" class="w-full">
                            <el-input class="w-11/12" type="textarea" v-model="formData.description"
                                      placeholder="请输入原因描述"
                                      clearable/>
                        </el-form-item>
                    </div>
                
                
                </div>
            
            </div>
        </el-card>
        
        <!--        物料-->
        <el-card class="!border-none    mt-8  " shadow="never">
            <el-button type="success" @click="handAddItemInfo">
                <icon name="el-icon-Plus"/>
                新增物料信息
            </el-button>
            
            
            <el-table
                v-loading="loading"
                ref="tableRef"
                class="mt-4 mb-60"
                size="large"
                :data="formData.itemInfo"
            
            >
                
                <el-table-column type="index" label="行号" width="70"/>
                
                
                <el-table-column label="售后69码" fixed prop="batch" min-width="220">
                    
                    <template #default="{row} ">
                        
                        <el-autocomplete
                            :disabled="!row.isDisabled"
                            class="w-full"
                            v-model="row.inMaterIalInfo.batch"
                            :fetch-suggestions="autocompleteQueryLineManager.querySearchAsync"
                            placeholder="请输入售后69码"
                            @select="autocompleteQueryLineManager.handleSelect(row.inMaterIalInfo)"
                            value-key="batch"
                        />
                    
                    </template>
                
                </el-table-column>
                
                <el-table-column label="售后物料编码" prop="itemCode" min-width="220">
                    <template #default="{row}">
                        <el-input
                            :disabled="!row.isDisabled"
                            placeholder="请输入售后物料编码"
                            clearable
                            v-model="row.inMaterIalInfo.itemCode">
                        
                        </el-input>
                    </template>
                </el-table-column>
                
                
                <el-table-column label="售后物料名称" prop="itemName" min-width="220">
                    <template #default="{row}">
                        <el-input
                            :disabled="!row.isDisabled"
                            placeholder="请输入售后物料名称"
                            clearable
                            v-model="row.inMaterIalInfo.itemName">
                        
                        </el-input>
                    </template>
                </el-table-column>
                
                
                <el-table-column label="售后SN" fixed prop="itemName" min-width="220">
                    <template #default="{row}">
                        <el-input
                            
                            :disabled="!row.isDisabled"
                            placeholder="请输入sn"
                            clearable
                            v-model="row.inMaterIalInfo.sn"
                        >
                        
                        
                        </el-input>
                    </template>
                </el-table-column>
                
                
                <el-table-column label="发出69码" fixed prop="itemName" min-width="220"
                                 v-if="formData.afterSaleOrderType=== AfterSaleOrderTypeEnum.CONSIGNMENT">
                    <template #default="{row}">
                        <el-autocomplete
                            :disabled="!row.isDisabled"
                            class="w-full"
                            v-model="row.outMaterialInfo.batch"
                            :fetch-suggestions="autocompleteQueryLineManager.querySearchAsync"
                            placeholder="请输入售后69码"
                            @select="autocompleteQueryLineManager.handleSelect(row.outMaterialInfo)"
                            value-key="batch"
                        />
                    
                    </template>
                </el-table-column>
                
                <el-table-column label="物料属性" fixed prop="itemName" min-width="220"
                                 v-if="formData.afterSaleOrderType === AfterSaleOrderTypeEnum.CONSIGNMENT">
                    <template #default="{row}">
                        <el-input
                            :disabled="!row.isDisabled"
                            placeholder="请输入物料属性"
                            clearable
                            v-model="row.outMaterialInfo.itemProperty">
                        
                        </el-input>
                    </template>
                </el-table-column>
                
                <el-table-column label="发出物料编码" prop="itemName" min-width="220"
                                 v-if="formData.afterSaleOrderType=== AfterSaleOrderTypeEnum.CONSIGNMENT">
                    <template #default="{row}">
                        <el-input
                            :disabled="!row.isDisabled"
                            placeholder="请输入发出物料编码"
                            clearable
                            v-model="row.outMaterialInfo.itemCode">
                        
                        </el-input>
                    </template>
                </el-table-column>
                
                <el-table-column label="发出物料名称" prop="itemName" min-width="220"
                                 v-if="formData.afterSaleOrderType=== AfterSaleOrderTypeEnum.CONSIGNMENT">
                    <template #default="{row}">
                        <el-input
                            :disabled="!row.isDisabled"
                            placeholder="请输入发出物料名称"
                            clearable
                            v-model="row.outMaterialInfo.itemName">
                        
                        </el-input>
                    </template>
                </el-table-column>
                
                
                <el-table-column label="操作" width="160" fixed="right">
                    <template #default="{ row }">
                        <el-button
                            v-if="!row.isDisabled"
                            @click="row.isDisabled=true"
                            type="primary"
                            link
                        >
                            编辑
                        </el-button>
                        
                        <el-button
                            v-if="row.isDisabled"
                            @click="editCurrentLine(row)"
                            type="primary"
                            link
                        >
                            固定
                        </el-button>
                    
                    </template>
                </el-table-column>
            
            </el-table>
        
        </el-card>
    
    
    </el-form>
    
    
    <footer-btns>
        <el-button type="primary" @click="handleSubmit">提交工单</el-button>
        <el-button type="primary" @click="testData">测试退</el-button>
        <el-button type="primary" @click="testData2">测试发</el-button>
    
    </footer-btns>

</template>

<script lang='ts' setup>


import {ShallowRef, UnwrapNestedRefs} from "@vue/reactivity";
import {shallowRef} from "vue";
import {FormInstance} from "element-plus";

import feedback from "@/utils/feedback";
import {useAfterSaleEnumManager} from "@/manager/base/AfterSaleEnumManager";
import router from "@/base/router";
import useMultipleTabsManager from "@/manager/base/MultipleTabsManager";
import {useRoute} from "vue-router";
import {createSerialNumberString} from "@/api/afterSale/order/AfterSaleOrderListController";
import RouterManager from "@/manager/base/RouterManager";
import {
    afterSaleOrderInfoOrLineAddOne,
    AfterSaleOrderInfoOrLineDTO
} from "@/api/afterSale/order/dto/AfterSaleOrderInfoOrLineDTO";
import {useFormatterManager} from "@/manager/base/FormatterManager";
import {useAutocompleteQueryLineManager} from "@/manager/base/AutocompleteQueryManager";
import {AfterSaleItemMaterialDTO} from "@/api/afterSale/order/dto/AfterSaleItemMaterialDTO";
import {AfterSaleAddressInfoRequest} from "@/api/afterSale/order/request/AfterSaleAddressInfoRequest";
import {AfterSaleOrderTypeEnum} from "@/config/enums/aftersale/AfterSaleOrderTypeEnum";
import AfterSaleItemLineInfoDTO from "@/api/afterSale/order/dto/AfterSaleItemLineInfoDTO";
import {createAfterSaleOrder} from "@/api/afterSale/order/AfterSaleOrderController";


let afterSaleOrderConfig = useAfterSaleEnumManager();
let formatterManager = useFormatterManager(afterSaleOrderConfig);
let multipleTabsManager = useMultipleTabsManager();
let autocompleteQueryLineManager = useAutocompleteQueryLineManager(afterSaleOrderConfig);


const formRef: ShallowRef = shallowRef<FormInstance>()
const loading = ref("");


/**
 * 地址选择
 *
 * @param value
 */
function handleAddressChange(value: string[]) {
    formData.addressInfoEnum = value
    formData.addressInfo.economize = value[0]
    formData.addressInfo.city = value[1]
    formData.addressInfo.county = value[2]
}

/**
 * 编辑当前行
 *
 * @param row
 */
function editCurrentLine(row: any) {
    row.isDisabled = !row.isDisabled;
}


/**
 * 新增一个物料节点
 */
function handAddItemInfo() {
    formData.itemInfo.push(new AfterSaleItemLineInfoDTO())
}


/**
 *  工单提交
 *
 * @author 徐寿春
 * 2023/4/5 17:12
 */
function handleSubmit() {
    
    formRef.value?.validate().then(() => {
            // 如果是售后工单自定义校验
            if (formData.afterSaleOrderType == "RETURN_ORDER") {
                for (let itemLineInfos of formData.itemInfo) {
                    if (!itemLineInfos?.inMaterIalInfo?.itemName) {
                        feedback.notifyWarning("售后物料名称不可为空")
                        return
                    }
                    if (!itemLineInfos.inMaterIalInfo.itemCode) {
                        feedback.notifyWarning("售后物料编码不可为空")
                        return
                    }
                    if (!itemLineInfos.inMaterIalInfo.batch) {
                        feedback.notifyWarning("售后物料69码不可为空")
                        return
                    }
                    if (!itemLineInfos.inMaterIalInfo.sn) {
                        feedback.notifyWarning("售后物料SN不可为空")
                        return
                    }
                }
                
                
            } else if (formData.afterSaleOrderType == "EXCHANGE_ORDER") {
                for (let itemLineInfos of formData.itemInfo) {
                    if (!itemLineInfos?.inMaterIalInfo?.itemName) {
                        feedback.notifyWarning("售后物料名称不可为空")
                        return
                    }
                    if (!itemLineInfos.inMaterIalInfo.itemCode) {
                        feedback.notifyWarning("售后物料编码不可为空")
                        return
                    }
                    if (!itemLineInfos.inMaterIalInfo.batch) {
                        feedback.notifyWarning("售后物料69码不可为空")
                        return
                    }
                    if (!itemLineInfos.inMaterIalInfo.sn) {
                        feedback.notifyWarning("售后物料SN不可为空")
                        return
                    }
                    
                }
                
                for (let itemLineInfos of formData.itemInfo) {
                    if (!itemLineInfos?.outMaterialInfo?.itemName) {
                        feedback.notifyWarning("发出物料名称不可为空")
                        return
                    }
                    if (!itemLineInfos.outMaterialInfo.itemCode) {
                        feedback.notifyWarning("发出物料编码不可为空")
                        return
                    }
                    if (!itemLineInfos.outMaterialInfo.batch) {
                        feedback.notifyWarning("发出物料69码不可为空")
                        return
                    }
                }
            }
            
            
            createAfterSaleOrder(formData).then(() => {
                
                multipleTabsManager.removeTab()
                
                let routePathByName = RouterManager.getRoutePathByName("afterSaleOrder/order/orderList/index");
                if (!!routePathByName) {
                    router.push(routePathByName)
                }
                
            })
            
        }
    )
}


/**
 * 生成唯一序列号
 */
async function createSerialNumber() {
    await createSerialNumberString().then(resp => {
        formData.orderNumber = resp
    })
    
}


/**
 * 渠道值改变
 *
 * @author 徐寿春
 * 2023/4/12 11:00
 */
function handleChannelChange() {

}


/**
 * 测试
 *
 * @author 徐寿春
 * 2023/5/4 17:21
 */
async function testData() {
    formData.afterSaleOrderType = "RETURN_ORDER"
    formData.source = "XT"
    formData.channel = "OFFLINE"
    formData.shopName = "OFFLINE-01"
    formData.userName = "userName"
    formData.userPhone = "123132"
    formData.reason = "NOREASON"
    await createSerialNumberString().then(resp => {
        formData.logisticCompany = resp
    })
    await createSerialNumberString().then(resp => {
        formData.logisticNumber = resp
    })
    
    formData.logisticCompany = "顺丰"
    let afterSaleItemLineInfoDTO1 = new AfterSaleItemLineInfoDTO();
    let afterSaleItemLineInfoDTO2 = new AfterSaleItemLineInfoDTO();
    
    let afterSaleItemMaterialDTO = new AfterSaleItemMaterialDTO();
    afterSaleItemMaterialDTO.itemName = "测试物料"
    afterSaleItemMaterialDTO.itemCode = "XPPP232132"
    
    afterSaleItemMaterialDTO.batch = "4234234"
    await createSerialNumberString().then(resp => {
        afterSaleItemMaterialDTO.sn = resp
    })
    
    let afterSaleItemMaterialDTO2 = new AfterSaleItemMaterialDTO();
    afterSaleItemMaterialDTO2.itemName = "测试物料"
    afterSaleItemMaterialDTO2.itemCode = "XPPP232132"
    afterSaleItemMaterialDTO2.batch = "4234234"
    await createSerialNumberString().then(resp => {
        afterSaleItemMaterialDTO2.sn = resp
    })
    
    
    afterSaleItemLineInfoDTO1.inMaterIalInfo = afterSaleItemMaterialDTO
    afterSaleItemLineInfoDTO2.inMaterIalInfo = afterSaleItemMaterialDTO2
    formData.itemInfo[0] = afterSaleItemLineInfoDTO1
    formData.itemInfo.push(afterSaleItemLineInfoDTO2)
    
    await createSerialNumber()
}


async function testData2() {
    
    formData.afterSaleOrderType = "EXCHANGE_ORDER"
    formData.source = "XT"
    formData.channel = "OFFLINE"
    formData.shopName = "OFFLINE-01"
    formData.userName = "userName"
    formData.userPhone = "123132"
    formData.reason = "NOREASON"
    
    await createSerialNumberString().then(resp => {
        formData.logisticNumber = resp
    })
    
    
    formData.logisticCompany = "顺丰"
    
    
    let afterSaleAddressInfoRequest = new AfterSaleAddressInfoRequest();
    afterSaleAddressInfoRequest.userName = "徐寿春"
    afterSaleAddressInfoRequest.userPhone = "3123123123"
    afterSaleAddressInfoRequest.city = "蚌埠"
    afterSaleAddressInfoRequest.economize = "安徽"
    afterSaleAddressInfoRequest.county = "东市区"
    afterSaleAddressInfoRequest.address = "3123123"
    
    formData.addressInfo = afterSaleAddressInfoRequest
    formData.addressInfoEnum = ["安徽", "蚌埠", "东市区"]
    
    
    let afterSaleItemLineInfoDTO1 = new AfterSaleItemLineInfoDTO();
    let afterSaleItemLineInfoDTO2 = new AfterSaleItemLineInfoDTO();
    
    let afterSaleItemMaterialDTO = new AfterSaleItemMaterialDTO();
    afterSaleItemMaterialDTO.itemName = "测试物料"
    afterSaleItemMaterialDTO.itemCode = "XPPP232132"
    afterSaleItemMaterialDTO.batch = "4234234"
    await createSerialNumberString().then(resp => {
        afterSaleItemMaterialDTO.sn = resp
    })
    
    let afterSaleItemMaterialDTO1_1 = new AfterSaleItemMaterialDTO();
    
    afterSaleItemMaterialDTO1_1.itemName = "测试物料"
    afterSaleItemMaterialDTO1_1.itemCode = "XPPP232132"
    afterSaleItemMaterialDTO1_1.batch = "123"
    afterSaleItemMaterialDTO1_1.itemProperty = "123"
    
    
    let afterSaleItemMaterialDTO2 = new AfterSaleItemMaterialDTO();
    afterSaleItemMaterialDTO2.itemName = "测试物料"
    afterSaleItemMaterialDTO2.itemCode = "XPPP232132"
    afterSaleItemMaterialDTO2.batch = "4234234"
    await createSerialNumberString().then(resp => {
        afterSaleItemMaterialDTO2.sn = resp
    })
    
    
    let afterSaleItemMaterialDTO2_2 = new AfterSaleItemMaterialDTO();
    
    afterSaleItemMaterialDTO2_2.itemName = "测试物料"
    afterSaleItemMaterialDTO2_2.itemCode = "XPPP232132"
    afterSaleItemMaterialDTO2_2.batch = "123"
    afterSaleItemMaterialDTO2_2.itemProperty = "123"
    
    
    afterSaleItemLineInfoDTO1.inMaterIalInfo = afterSaleItemMaterialDTO
    afterSaleItemLineInfoDTO1.outMaterialInfo = afterSaleItemMaterialDTO1_1
    
    afterSaleItemLineInfoDTO2.inMaterIalInfo = afterSaleItemMaterialDTO2
    afterSaleItemLineInfoDTO2.outMaterialInfo = afterSaleItemMaterialDTO2_2
    formData.itemInfo[0] = afterSaleItemLineInfoDTO1
    formData.itemInfo.push(afterSaleItemLineInfoDTO2)
    
    await createSerialNumber()
}


/**
 * 监听渠道 监听店铺
 *
 * @author 徐寿春
 * 2023/4/12 08:35
 */
const shopSelect = computed(() => {
    return formatterManager.computeFormatterShop(formData.channel)
})

const channelSelect = computed(() => {
    return formatterManager.computeFormatterChannel(formData.shopName)
})


/**
 * 如果是编辑反查询
 */
let formData: UnwrapNestedRefs<AfterSaleOrderInfoOrLineDTO> = reactive(afterSaleOrderInfoOrLineAddOne());


let route = useRoute();
let watchEffect1 = watchEffect(() => {
    formData.afterSaleOrderId = route.query?.id as any
});
watchEffect1()


</script>





